﻿using Microsoft.EntityFrameworkCore;
using Shop.Application.Products.Dto;
using Shop.DB;
using Shop.Domain.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shop.Application.Products
{
    public class GetProductByName
    {
        private DBContext _context;
        public GetProductByName(DBContext context)
        {
            _context = context;
        }

        public async Task<ProductDto> Do(string name)
        {
            var stockHold = _context.StockHolds.Where(x => x.ExpiryDate < DateTime.Now).ToList();
            if (stockHold.Count > 0)
            {
                var stockReturn = _context.Stocks.AsEnumerable().Where(x => stockHold.Any(y => y.StockID == x.StockID)).ToList();
                foreach (var item in stockReturn)
                {
                    item.Count += stockHold.FirstOrDefault(x => x.StockID == item.StockID).Count;
                }
                _context.StockHolds.RemoveRange(stockHold);
                await _context.SaveChangesAsync();
            }

            return _context.Products
              .Include(x => x.Stocks)
              .Where(x => x.Name == name)
              .Select(x => new ProductDto
              {
                  ID = x.ProductID,
                  Name = x.Name,
                  Description = x.Description,
                  Value = $"¥{x.Value.ToString("N2")}"
              }).FirstOrDefault();
        }
    }
}
